package com.fairytask.extention.user;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import com.fairytask.extention.LoginExtention;
import com.fairytask.extention.define.CustomToClientDefine;
import com.qq.open.OpensnsException;
import com.smartfoxserver.v2.SmartFoxServer;
import com.smartfoxserver.v2.api.ISFSUtilApi;
import com.smartfoxserver.v2.db.IDBManager;
import com.smartfoxserver.v2.entities.SFSUser;
import com.smartfoxserver.v2.entities.User;
import com.smartfoxserver.v2.entities.data.ISFSArray;
import com.smartfoxserver.v2.entities.data.ISFSObject;
import com.smartfoxserver.v2.entities.data.SFSObject;
import com.smartfoxserver.v2.entities.variables.SFSUserVariable;
import com.smartfoxserver.v2.entities.variables.UserVariable;
import com.smartfoxserver.v2.entities.variables.VariableType;
import com.smartfoxserver.v2.exceptions.SFSVariableException;

/**
 * 用户管理 
 * @author jzonl
 */
/**
 * @author jzonl
 *
 */
public class UserManager
{
	private LoginExtention	loginExt;
	private IDBManager dbManager;
	//请求参数
	private HashMap<String, String> apiParams;
	private User user;
	
	public UserManager(LoginExtention pExt)
	{
		loginExt	=	pExt;
		dbManager	=	pExt.getParentZone().getDBManager();
		apiParams		=	new HashMap<String, String>();
	}

	public void userCheck(SFSObject pInfo,User user)
	{
		String sql	=	"select username,nickname,model from users where username='"+pInfo.getUtfString("openid")+"' ";
		// Obtain a resultset
		try
		{
			ISFSArray res = dbManager.executeQuery(sql);
			System.out.println("用户数据:"+res);
			System.out.println("sql:"+sql);
			//用户不存在 直接注册个
			if(res.size()==0)
			{
				pInfo.putBool("isNew", true);
			}
			else
			{
				pInfo.putBool("isNew", false);
				pInfo.putUtfString("nickname", res.getSFSObject(0).getUtfString("nickname"));
				pInfo.putUtfString("model", res.getSFSObject(0).getUtfString("model"));
				SFSUserVariable userVari	=	new SFSUserVariable("info", pInfo);
				try
				{
					List<UserVariable> vList	=	new ArrayList<UserVariable>();
					vList.add(userVari);
					loginExt.getApi().setUserVariables(user, vList);
					user.setVariable(userVari);
				} catch (SFSVariableException e)
				{
					System.out.println("::::::::::::::::::::::::ERRO SET::::::::::::::::::::::::::::::::");
					e.printStackTrace();
				}
				//user.setProperty("info", pInfo);
			}
			loginExt.send(CustomToClientDefine.USER_INFO, pInfo, user);
		} catch (SQLException e)
		{
			e.printStackTrace();
		}
	}
	
	/**
	 * 检查用户名 存在为false
	 * 可用为true
	 * 不可用为false
	 * @param nick
	 * @return
	 * @throws SQLException
	 */
	public Boolean checkNick(String nick) throws SQLException
	{
		String sql	=	"select nickname from users where nickname='"+nick+"' ";
		return getSqlQuery(sql).size()==0;
	}
	
	/**
	 * 用户注册
	 * @param pInfo
	 * @param user
	 */
	public void userRegister(ISFSObject pInfo,User user)
	{
		String sql	=	"INSERT INTO `users` (`username`,`pword`,`city`,`nickname`,`model`,`gender`,`viptype`) VALUES ";
		sql	+=	"('"+pInfo.getUtfString("openid")+"', '123', '"+pInfo.getUtfString("city")+"', '"+pInfo.getUtfString("nickname")+"', '"+pInfo.getUtfString("model")+"', '"+pInfo.getInt("gender")+"', "+pInfo.getInt("is_yellow_vip")+");";
		System.out.println("查询语句:"+sql);
		try
		{
			dbManager.executeUpdate(sql);
		}
		catch (SQLException e)
		{
			System.out.println("::::::用户注册失败::::::::::::::::::::");
		}
		try
		{
			setUserVars(user, pInfo.getUtfString("nickname"), pInfo.getUtfString("model"));
		} 
		catch (SFSVariableException e)
		{
			System.out.println("::::::设置用户变量失败::::::::::::::::::::");
		}
	}
	
	public void initApi(String openid,String openkey,User user)
	{
		apiParams.clear();
		apiParams.put("openid", openid);
		apiParams.put("openkey", openkey);
		this.user	=	user;
	}
	
	/**
	 * 查询
	 * @param sql
	 * @return
	 * @throws SQLException
	 */
	private ISFSArray getSqlQuery(String sql) throws SQLException
	{
		ISFSArray res = dbManager.executeQuery(sql);
		return res;
	}
	
	/**
	 * 添加用户的自定义属性
	 * @param pUser
	 * @param pData
	 * @throws SFSVariableException
	 */
	private void setUserVars(User pUser, SFSObject pData) throws SFSVariableException
	{
		SFSUserVariable userVari	=	new SFSUserVariable("info", pData);
		List<UserVariable> vList	=	new ArrayList<UserVariable>();
		vList.add(userVari);
		loginExt.getApi().setUserVariables(pUser, vList);
		pUser.setVariable(userVari);
	}
	
	private void setUserVars(User pUser,String pName, String pModel) throws SFSVariableException
	{
		SFSObject userObj	=	new SFSObject();
		userObj.putUtfString("nickname", pName);
		userObj.putUtfString("model", pModel);
		setUserVars(pUser,userObj);
	}
	
	/**
	 * 取得用户信息 同时设置附加属性
	 * @return
	 * @throws OpensnsException
	 * @throws SQLException
	 */
	public SFSObject getUserInfo() throws OpensnsException, SQLException
	{
		SFSObject	userObj	=	new SFSObject();
		if(!checkLogin())
		{
			loginExt.send(CustomToClientDefine.USER_RELOGIN, userObj, user);
			System.out.println("not login and send the message!!--------");
			return null;
		}
		//直接查询有没有这个人
		String sql	=	"select username,nickname,model from users where username='"+apiParams.get("openid")+"' ";
		ISFSArray	dbResult	=	getSqlQuery(sql);
		if(dbResult.size()>0)
		{
			userObj.putBool("isNew", false);
			userObj.putUtfString("nickname", dbResult.getSFSObject(0).getUtfString("nickname"));
			userObj.putUtfString("model", dbResult.getSFSObject(0).getUtfString("model"));
			
			try
			{
				setUserVars(user,userObj);
			}
			catch (SFSVariableException e)
			{
				System.out.println("::::::ERRO WHEN SET USER VARIABLES::::::::::::::::::::");
			}
		}
		else
		{
			userObj.putBool("isNew", true);
		}
		return userObj;
	}
	
	/**
	 * 检查是否登陆
	 * @param openid
	 * @param openkey
	 * @return
	 * @throws OpensnsException
	 */
	public Boolean	checkLogin() throws OpensnsException
	{
		return true;
//		SFSObject	userObj	=	getApiData("/v3/user/is_login",apiParams);
//		int retInfo	=	userObj.getInt("ret");
//		return retInfo==0;
	}
	
	/**
	 *  取得数据
	 * @param openApi
	 * @param params
	 * @return
	 * @throws OpensnsException
	 */
	public SFSObject	getApiData(String openApi,HashMap<String, String> params) throws OpensnsException
	{
		SFSObject	userObj	=	new SFSObject();
		if(!params.containsKey("pf"))
		{
			params.put("pf", LoginExtention.pf);
		}
		String userInfo	=	LoginExtention.OpenApi.api(openApi, params,"http");
		userObj	=	SFSObject.newFromJsonData(userInfo);
		userObj.putUtfString("openid", apiParams.get("openid"));
		return userObj;
	}
}
